<?php
defined('_JEXEC') or die('Restricted access');

require_once(JPATH_COMPONENT.DS.'persistance'.DS.'DAOInfo.php');
require_once(JPATH_COMPONENT.DS.'domain'.DS.'DTOInfo.php');

class DAOInfoImpl implements DAOInfo{
	
	public function addInfo($con, $dtoInfo){
		if(!$this->checkInfo($con, $dtoInfo->getIsoCode(), $dtoInfo->getIdWord())){
			$data = new stdClass();
			$data->iso_code = $dtoInfo->getIsoCode();
			$data->id_word = $dtoInfo->getIdWord();
			$data->spelling = $dtoInfo->getSpelling();
			$data->pronoun = $dtoInfo->getPronoun();
			$data->video_path = $dtoInfo->getVideoPath();
			$data->active = $dtoInfo->isActive();

			if(!$con->insertObject( '#__hizkuntzak_lang_words', $data)){
				echo $con->stderr();
				return false;
			}
			else 
				return true;	
		}
		else{
			
			return $this->updateInfo($con, $dtoInfo);
		}
		return false;
	}
	
	public function updateInfo($con, $dtoInfo){
		
		$sql = "UPDATE #__hizkuntzak_lang_words SET spelling='$dtoInfo->spelling', ";
		$sql = $sql."pronoun='$dtoInfo->pronoun', video_path='$dtoInfo->videoPath', ";
		$sql = $sql."active=$dtoInfo->active WHERE iso_code='$dtoInfo->iso_code' and id_word=$dtoInfo->idWord ";

		$con->setQuery($sql);
		
		if(!$con->query()){
			$con->stderr();
			return false;
		}
		else
			return true;
	}
	
	public function checkInfo($con, $lang_code, $idWord){
		$sql = "select * from #__hizkuntzak_lang_words where (iso_code='$lang_code' AND id_word=$idWord)";
		
		$con->setQuery($sql);
		
    	$row = $con->loadObject();
    	
    	if($row == null || $row == ""){
    		return false;
    	}
    	return true;
	}
	
	public function getLangInfo($con, $lang_code, $active){
		$results = array();
		
		$sql = "SELECT #__hizkuntzak_lang_words . * , #__hizkuntzak_words.word_es, #__hizkuntzak_words.word_eu, #__hizkuntzak_languages.name_es, #__hizkuntzak_languages.name_eu
			FROM #__hizkuntzak_words
			LEFT JOIN #__hizkuntzak_lang_words ON #__hizkuntzak_lang_words.id_word = #__hizkuntzak_words.id
			LEFT JOIN #__hizkuntzak_languages ON #__hizkuntzak_lang_words.iso_code = #__hizkuntzak_languages.iso_code
			WHERE #__hizkuntzak_lang_words.iso_code='$lang_code'";
		
		if($active){
			$sql = $sql. "AND #__hizkuntzak_lang_words.active=1 ";
		}

		$con->setQuery($sql);
		
    	$objectList = $con->loadObjectList();

        foreach($objectList as $row) {
        	
        	$info = new DTOInfo();
        	
        	$info->setIsoCode($row->iso_code);
        	$info->setNameEs($row->name_es);
        	$info->setNameEu($row->name_eu); 
        	$info->setIdWord($row->id_word);
        	$info->setWordEs($row->word_es);
        	$info->setWordEu($row->word_eu);
        	$info->setSpelling($row->spelling);
        	$info->setPronoun($row->pronoun);
        	$info->setVideoPath($row->video_path);
        	$info->setActive($row->active);
            
        	$results[] = $info;
          } 
		
		return $results;
	}
}